package
{
    
    import com.terrynoya.Resource.ExternalClassLoader;
    import com.terrynoya.Resource.ExternalResManager;
    import com.terrynoya.Resource.events.ExternalClassLoaderEvent;
    import com.terrynoya.Resource.events.ExternalResManagerEvent;
    
    import flash.display.DisplayObject;
    import flash.display.Sprite;
    import flash.system.ApplicationDomain;

    /**
     * 外部类管理example
     * @author TerryYao
     */
    public class ResourceLoaderTest extends Sprite
    {
    	private var objTotalX:Number = 0;
        /**
         * 使用方法
         * 1.让manager配置一下config
         * 2.监听init事件，配置完成后可以使用ExternalClassLoader,传一个类名给Loader
         * 3.监听Loader.Complete事件,顺利完成后可以在ApplicationDomain.currentDomain.getDefinition(className)得到加载好的Class
         */
        public function ResourceLoaderTest()
        {
            ExternalResManager.instance().loadConfig("assets/catalog.xml");
            ExternalResManager.instance().addEventListener(ExternalResManagerEvent.INITED, onInit);
        }
		
        private function onInit(e:ExternalResManagerEvent):void
        {
			this.loadClass("cl001");
			this.loadClass("cl002");
			this.loadClass("notExistClassName");
        } 
		
		private function loadClass(className:String):void
		{
			var ld:ExternalClassLoader = new ExternalClassLoader(className);
            ld.addEventListener(ExternalClassLoaderEvent.COMPLETE, onLoadComp);
            ld.addEventListener(ExternalClassLoaderEvent.IO_ERROR, onLoadError);
            ld.addEventListener(ExternalClassLoaderEvent.CLASS_NOT_FOUND, classNotFoundError);
            ld.load();	
		}
		
        private function onLoadComp(e:ExternalClassLoaderEvent):void
        {
        	trace("onLoadComp");
            var ld:ExternalClassLoader = ExternalClassLoader(e.currentTarget);
            var myclass:Class = ApplicationDomain.currentDomain.getDefinition(ld.name) as Class;
            var bmp:DisplayObject = new myclass;
            bmp.x = objTotalX;
            objTotalX += bmp.width;
            this.stage.addChild(bmp);
        }
        
        private function onLoadError(e:ExternalClassLoaderEvent):void
        {
        	trace("Error");
        }
        
        private function classNotFoundError(e:ExternalClassLoaderEvent):void
        {
        	trace("Class not found");
        }
    }
}

